package com.xinxin.websocket.controller;

import com.xinxin.websocket.dataobject.User;
import com.xinxin.websocket.response.Response;
import com.xinxin.websocket.service.UserService;
import com.xinxin.websocket.utils.ResponseUtils;
import com.xinxin.websocket.utils.WebSocketUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;

/**
 * @author ：史鑫鑫
 * @date ：Created in 2019/4/28 14:09
 */
@RestController
public class WebSocketController extends HttpServlet {
    @Autowired
    UserService service;
    /**
     * 用户登录
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/login")
    public Response login(@RequestBody User user, HttpSession session) {
        System.out.println("用户登录");
        if (user.getName() == null || "".equals(user.getName())) {
            return ResponseUtils.error(201, "未知用户");
        }
        session.setAttribute("user", user);
        System.out.println("user = " + session.getAttribute("user"));
        service.insert(user);
        return ResponseUtils.success("登陆成功", user);
    }

    /**
     * 用户注销
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public Response UserLogout(HttpSession session) {
        System.out.println("用户注销");
        session.removeAttribute("user");
        User user = (User) session.getAttribute("user");
        if (user != null) {
            return ResponseUtils.error(201, "注销失败");
        }
        return ResponseUtils.success("注销成功");
    }

    /**
     * 获取当前用户信息
     * @param session
     * @return
     */
    @GetMapping("/selfInfo")
    public Response selfInfo(HttpSession session) {
        User user = (User) session.getAttribute("user");
        return ResponseUtils.success("成功", user);
    }
}
